package completablefuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Stream;

/**
 * allOf().join等待所有异步任务的执行
 */
public class Test5 {
    public static void main(String[] args) {
        MyUtil.currentDate("执行前");
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            MyUtil.sleep(1000);
            return 1;
        });

        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            MyUtil.sleep(2000);
            return 2;
        });

        CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(() -> {
            MyUtil.sleep(3000);
            return 3;
        });

        // 阻塞等待执行
        CompletableFuture.allOf(future1, future2, future3).join();
        Integer min = Stream.of(future1, future2, future3).map(item -> {
            try {
                return item.get();
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
            return null;
        }).sorted().findFirst().orElseThrow(() -> new RuntimeException("没有最小值"));

        System.out.println("最小值为 " + min);

        MyUtil.currentDate("执行后");
    }
}
